package com.lian.chatroom.server.handler;

import com.lian.chatroom.message.LoginRequestMessage;
import com.lian.chatroom.message.LoginResponseMessage;
import com.lian.chatroom.server.service.UserServiceFactory;
import com.lian.chatroom.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 登录请求消息处理器
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        Boolean login = UserServiceFactory.getUserService().login(username, password);
        //登录响应消息
        LoginResponseMessage message;
        if (login){
            //如果登录成功,将此成功登录用户的用户名和通道绑定，一起存放到map中
            SessionFactory.getSession().bind(ctx.channel(),username);
            message = new LoginResponseMessage(true,"登录成功");
        }else {
            //如果登录失败
            message = new LoginResponseMessage(false,"用户名或密码不正确");
        }
        //将消息写入到通道中
        ctx.writeAndFlush(message);
    }
}
